package com.lianzai.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.lianzai.common.annotation.NoLoginAuthRequired;
import com.lianzai.common.config.WxConfig;
import com.lianzai.common.constant.Constant;
import com.lianzai.common.utils.WxUtil;
import com.lianzai.mobile.domain.WxUserDO;
import com.lianzai.mobile.service.WxUserService;
import com.lianzai.user.domain.UserInfoDO;
import com.lianzai.user.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * Created by zb on 15/6/2017.
 */
@Slf4j
@Component
public class UserAuthInterceptor extends HandlerInterceptorAdapter {

    @Value("${server.domain-index}")
    private String baseUrl;

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getRequestURI();
        log.info("拦截器URL : " + path);
        if(path.indexOf("/mobile") != 0 && path.indexOf("//mobile") != 0){
            return true;
        }
        if(path.indexOf("//mobile") != 0){
            path = path.substring(1, path.length());
        }

        try {
            HttpSession session = request.getSession();
//            session.setAttribute(Constant.CURR_OPEN_ID, "12345678s9");
            String openid = (String) session.getAttribute(Constant.CURR_OPEN_ID);

            if(StringUtils.isEmpty(openid)){
                String code = request.getParameter("code");

                if(StringUtils.isEmpty(code)){
                    log.info("跳入微信授权页获取code");
                    String redirectUrl = WxUtil.connectOauth2Authorize(wxConfig.getAppid(), baseUrl.concat("/").concat(path));
                    log.info("跳转到微信授权页 redirectUrl : {}", redirectUrl);

                    response.sendRedirect(redirectUrl);
                    return false;
                } else {
                    log.info("微信授权 code : {}", code);
                    JSONObject json = WxUtil.getOpenIdByJsCode(code, wxConfig.getAppid(), wxConfig.getAppsecret());
                    log.info("根据Code获取微信信息 result : {}", json.toString());
                    session.setAttribute(Constant.CURR_OPEN_ID, json.get("openid"));
                    openid = json.get("openid").toString();
                    return judgeJumpUrl(openid, session, response, path, handler);
                }
            } else {
                return judgeJumpUrl(openid, session, response, path, handler);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }


    private Boolean judgeJumpUrl(String openid, HttpSession session, HttpServletResponse response, String path, Object handler)throws Exception{
        //判断用户是否注册
        WxUserDO wxUser = wxUserService.getByOpenId(openid);
        if(wxUser==null || wxUser.getUserId()==null){
            if(wxUser == null && openid != null){
                wxUser = new WxUserDO();
                wxUser.setOpenId(openid);
                wxUser.setIsAttention("nosubscribe");
                wxUserService.save(wxUser);
            }

            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            NoLoginAuthRequired noLoginAuthRequired = method.getAnnotation(NoLoginAuthRequired.class);
            if(noLoginAuthRequired != null) {  //不需要登录直接放行
                return true;
            }

            log.info("跳转到注册绑定页面 url : {}", baseUrl.concat("/mobile/register"));
            response.sendRedirect(baseUrl.concat("/mobile/register"));
            return false;
        }else {
            UserInfoDO userInfo = userInfoService.get(wxUser.getUserId());
            session.setAttribute(Constant.CURR_USER_INFO, userInfo);
            session.setAttribute(Constant.CURR_USER_ID, userInfo.getId());
            session.setAttribute(Constant.CURR_USER_MOBILE, userInfo.getMobile());
            log.info("跳转到指定页面 url : {}", path);
            return true;
        }
    }
}
